package com.vip.mvc.utils.objectpool;

import com.vip.mvc.annotation.PostConstruct;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.lang.reflect.Method;

/**
 * Created by cloudy.xie on 17/2/16.
 */
public class MyPoolableObjectFactory extends BasePooledObjectFactory<Object> {
    private String objName;

    public MyPoolableObjectFactory(String objName){
        super();
        this.objName = objName;
    }

    /**
     * 创建一个对象实例
     */
    @Override
    public Object create() throws Exception {
        Class c = Class.forName(objName);
        Object obj = c.newInstance();
        Method[] methodArr = obj.getClass().getMethods();
        if(methodArr == null || methodArr.length<=0){
            return obj;
        }

        for (Method method : methodArr){
            if(method.isAnnotationPresent(PostConstruct.class)){
                method.invoke(obj);
            }
        }
        return obj;
    }

    /**
     * 包裹创建的对象实例，返回一个pooledobject
     */
    @Override
    public PooledObject<Object> wrap(Object obj) {
        return new DefaultPooledObject<>(obj);
    }

}
